import CryptoUtil from './utils/crypto.js';

class PasswordManager {
    constructor() {
        this.crypto = null;
        this.entries = [];
        this.clickTimer = null;
        this.clickDelay = 300; // 毫秒，用于判断单击和双击
        this.init();
    }

    async init() {
        // 初始化UI事件监听
        this.initUIEvents();
        
        // 加载设置
        await this.loadSettings();
        
        // 加载已保存的条目
        await this.loadEntries();
    }

    initUIEvents() {
        // 标签页切换
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', () => this.switchTab(btn.dataset.tab));
        });

        // 添加新条目表单
        const addForm = document.getElementById('add-form');
        if (addForm) {
            addForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.addEntry();
            });
        }

        // 搜索功能
        const searchInput = document.getElementById('search');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.filterEntries(e.target.value);
            });
        }

        // 保存设置
        const saveSettingsBtn = document.getElementById('save-settings');
        if (saveSettingsBtn) {
            saveSettingsBtn.addEventListener('click', () => {
                this.saveSettings();
            });
        }

        // 立即同步
        const syncNowBtn = document.getElementById('sync-now');
        if (syncNowBtn) {
            syncNowBtn.addEventListener('click', () => {
                this.syncData();
            });
        }
    }

    async loadSettings() {
        // 从 chrome.storage.local 加载设置
        const settings = await chrome.storage.local.get(['masterKey', 'syncUrl', 'deviceId']);
        if (settings.masterKey) {
            this.crypto = new CryptoUtil(settings.masterKey);
            document.getElementById('master-key').value = settings.masterKey;
        }
        if (settings.syncUrl) {
            document.getElementById('sync-url').value = settings.syncUrl;
        }
        if (settings.deviceId) {
            document.getElementById('device-id').value = settings.deviceId;
        }
    }

    async loadEntries() {
        const settings = await chrome.storage.local.get(['deviceId']);
        if (!settings.deviceId) {
            console.log('No device ID set, cannot load entries');
            return;
        }
        
        const encryptedData = await chrome.storage.local.get(`entries_${settings.deviceId}`);
        if (encryptedData[`entries_${settings.deviceId}`] && this.crypto) {
            try {
                const decryptedEntries = await this.crypto.decrypt(encryptedData[`entries_${settings.deviceId}`]);
                this.entries = Array.isArray(decryptedEntries) ? decryptedEntries : [];
                this.renderEntries();
            } catch (error) {
                console.error('Failed to decrypt entries:', error);
                showMessage('解密数据失败，请检查主密钥是否正确', 'error');
            }
        } else {
            this.entries = [];
            this.renderEntries();
        }
    }

    async addEntry() {
        try {
            if (!this.crypto) {
                showMessage('请先设置主密钥', 'error');
                return;
            }

            const url = document.getElementById('url').value.trim();
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();
            const notes = document.getElementById('notes').value.trim();
            const addForm = document.getElementById('add-form');
            const editId = addForm ? addForm.dataset.editId : null;

            // 表单验证
            if (!url) {
                showMessage('请输入网址', 'error');
                return;
            }
            if (!username) {
                showMessage('请输入用户名', 'error');
                return;
            }
            if (!password) {
                showMessage('请输入密码', 'error');
                return;
            }

            // 详细记录编辑状态
            if (editId) {
                console.log('正在编辑记录，ID:', editId, '类型:', typeof editId);
                
                // 输出当前所有记录的ID，方便比较
                console.log('当前所有记录ID:', this.entries.map(e => ({id: e.id, type: typeof e.id})));
            } else {
                console.log('正在创建新记录');
            }

            let isEdit = false;
            let editIndex = -1;
            
            // 如果是编辑，先查找对应记录
            if (editId) {
                // 转换ID为数字，确保类型一致
                const numericId = Number(editId);
                
                if (isNaN(numericId)) {
                    console.error('ID 转换为数字失败:', editId);
                    showMessage('编辑失败：无效的记录ID', 'error');
                    return;
                }
                
                // 查找记录
                editIndex = this.entries.findIndex(e => Number(e.id) === numericId);
                
                if (editIndex !== -1) {
                    isEdit = true;
                    console.log('找到要编辑的记录，索引:', editIndex, '记录ID:', this.entries[editIndex].id);
                } else {
                    console.error('未找到要编辑的记录，ID:', numericId);
                    showMessage('要编辑的记录不存在', 'error');
                    return;
                }
            }

            // 创建条目对象
            const entry = {
                id: isEdit ? Number(this.entries[editIndex].id) : Date.now(), // 保持原ID或生成新ID
                url,
                username,
                password,
                notes,
                createdAt: isEdit ? this.entries[editIndex].createdAt : new Date().toISOString(),
                updatedAt: new Date().toISOString()
            };

            // 保存或更新记录
            if (isEdit) {
                console.log('更新记录，索引:', editIndex, '新数据:', entry);
                this.entries[editIndex] = entry;
            } else {
                console.log('添加新记录:', entry);
                this.entries.push(entry);
            }

            // 保存数据
            console.log('保存所有记录...');
            const saveResult = await this.saveEntries();
            
            if (saveResult) {
                // 清除表单和编辑状态
                this.clearForm();
                
                // 切换到查看标签页
                this.switchTab('view');
                
                // 显示成功消息
                showMessage(isEdit ? '记录已更新' : '记录已添加', 'success');
                
                // 自动同步到服务器
                try {
                    await this.uploadToServer('update');
                    showMessage('数据已同步到服务器', 'success');
                } catch (error) {
                    console.error('同步数据失败:', error);
                    showMessage('同步到服务器失败: ' + error.message, 'error');
                }
            }
        } catch (error) {
            console.error('添加/编辑记录失败:', error);
            showMessage('操作失败: ' + error.message, 'error');
        }
    }

    async saveEntries() {
        try {
            if (!this.crypto) {
                console.error('Crypto not initialized');
                showMessage('加密功能未初始化', 'error');
                return false;
            }

            const settings = await chrome.storage.local.get(['deviceId']);
            if (!settings.deviceId) {
                console.error('No device ID set, cannot save entries');
                showMessage('请先设置设备ID', 'error');
                return false;
            }

            console.log('Encrypting entries:', this.entries);
            const encryptedData = await this.crypto.encrypt(this.entries);
            
            console.log('Saving to chrome.storage.local');
            await chrome.storage.local.set({ [`entries_${settings.deviceId}`]: encryptedData });
            
            console.log('Save successful');
            // 保存成功后立即更新显示
            this.renderEntries();
            return true;
        } catch (error) {
            console.error('Save failed:', error);
            showMessage('保存失败: ' + error.message, 'error');
            return false;
        }
    }

    async saveSettings() {
        const masterKey = document.getElementById('master-key').value;
        const syncUrl = document.getElementById('sync-url').value;
        const deviceId = document.getElementById('device-id').value;

        if (!masterKey) {
            alert('主密钥不能为空');
            return;
        }

        // 使用 chrome.storage.local 存储设置，这样不会自动同步
        await chrome.storage.local.set({
            masterKey,
            syncUrl,
            deviceId
        });

        this.crypto = new CryptoUtil(masterKey);
        showMessage('设置已保存，请在其他设备上输入相同的主密钥和同步地址','success');
    }

    async syncData() {
        try {
            console.log('Starting manual sync...');
            // 从 chrome.storage.local 获取设置
            const settings = await chrome.storage.local.get(['masterKey', 'syncUrl', 'deviceId']);
            if (!settings.masterKey || !settings.syncUrl) {
                console.log('Sync skipped: Missing masterKey or syncUrl');
                showMessage('请先设置主密钥和同步URL', 'error');
                return;
            }

            if (!settings.deviceId) {
                console.log('Sync skipped: Missing deviceId');
                showMessage('请先设置设备ID', 'error');
                return;
            }

            // 创建当前设备的加密工具
            const localCrypto = new CryptoUtil(settings.masterKey);
            const encryptedData = await chrome.storage.local.get(`entries_${settings.deviceId}`);
            
            // 如果有本地数据，先验证主密钥
            if (encryptedData[`entries_${settings.deviceId}`]) {
                try {
                    // 尝试解密数据来验证主密钥
                    await localCrypto.decrypt(encryptedData[`entries_${settings.deviceId}`]);
                    console.log('Local master key validation successful');
                } catch (error) {
                    console.error('Local master key validation failed:', error);
                    showMessage('主密钥错误，请检查后重试', 'error');
                    return;
                }
            }

            // 创建数据备份
            const backup = {
                timestamp: new Date().toISOString(),
                data: encryptedData[`entries_${settings.deviceId}`]
            };
            await chrome.storage.local.set({ [`backup_${settings.deviceId}`]: backup });

            console.log('Retrieving local data...');
            
            // 1. 先获取服务器数据
            console.log('Fetching server data...');
            const getResponse = await fetch(`${settings.syncUrl}?device_id=${settings.deviceId}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!getResponse.ok) {
                throw new Error(`Failed to fetch server data: ${getResponse.status}`);
            }

            const serverResponse = await getResponse.json();
            if (!serverResponse.success) {
                throw new Error(`Server error: ${serverResponse.error}`);
            }

            console.log('Server data received:', serverResponse);

            // 2. 合并本地和服务器数据
            let mergedEntries = [];
            
            // 处理本地数据
            if (encryptedData[`entries_${settings.deviceId}`]) {
                try {
                    const localEntries = await localCrypto.decrypt(encryptedData[`entries_${settings.deviceId}`]);
                    mergedEntries = [...localEntries];
                } catch (error) {
                    console.error('Failed to decrypt local data:', error);
                    // 如果本地数据解密失败，尝试从备份恢复
                    const backupData = await chrome.storage.local.get(`backup_${settings.deviceId}`);
                    if (backupData[`backup_${settings.deviceId}`]) {
                        try {
                            const backupEntries = await localCrypto.decrypt(backupData[`backup_${settings.deviceId}`].data);
                            mergedEntries = [...backupEntries];
                            showMessage('使用备份数据恢复成功', 'success');
                        } catch (backupError) {
                            console.error('Backup recovery failed:', backupError);
                            showMessage('数据恢复失败，请检查主密钥', 'error');
                            return;
                        }
                    }
                }
            }

            // 处理服务器数据
            if (serverResponse.data) {
                try {
                    // 尝试使用本地密钥解密服务器数据
                    const serverEntries = await localCrypto.decrypt(serverResponse.data);
                    console.log('Server data decrypted with local key');
                    
                    // 合并策略：保留最新的版本
                    serverEntries.forEach(serverEntry => {
                        const existingIndex = mergedEntries.findIndex(e => e.id === serverEntry.id);
                        if (existingIndex === -1) {
                            // 新条目，直接添加
                            mergedEntries.push(serverEntry);
                        } else {
                            // 比较更新时间
                            const localUpdated = new Date(mergedEntries[existingIndex].updatedAt || mergedEntries[existingIndex].createdAt);
                            const serverUpdated = new Date(serverEntry.updatedAt || serverEntry.createdAt);
                            
                            if (serverUpdated > localUpdated) {
                                // 服务器数据更新，使用服务器数据
                                mergedEntries[existingIndex] = serverEntry;
                            }
                        }
                    });
                } catch (serverDecryptError) {
                    console.log('Failed to decrypt server data with local key, trying to merge without decryption');
                    // 如果无法解密服务器数据，保持本地数据不变
                    showMessage('无法解密服务器数据，请检查主密钥是否正确', 'error');
                    return;
                }
            }

            // 3. 将合并后的数据上传到服务器
            console.log('Uploading merged data to server...');
            const encryptedMergedData = await localCrypto.encrypt(mergedEntries);
            const postResponse = await fetch(settings.syncUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 
                    data: encryptedMergedData,
                    device_id: settings.deviceId,
                    operation: 'update'
                })
            });

            if (!postResponse.ok) {
                throw new Error(`Failed to upload data: ${postResponse.status}`);
            }

            const postResult = await postResponse.json();
            if (!postResult.success) {
                throw new Error(`Server error: ${postResult.error}`);
            }

            // 4. 保存合并后的数据到本地
            await chrome.storage.local.set({ [`entries_${settings.deviceId}`]: encryptedMergedData });
            this.entries = mergedEntries;
            this.renderEntries();

            console.log('Sync completed successfully');
            showMessage('同步成功', 'success');
        } catch (error) {
            if (error.message.includes('401')) {
                showMessage('账号错误,不存在', 'error');
            } else {
                showMessage('同步失败: ' + error.message, 'error');
            }
        }
    }

    filterEntries(query) {
        const filtered = this.entries.filter(entry => 
            entry.url.toLowerCase().includes(query.toLowerCase()) ||
            entry.username.toLowerCase().includes(query.toLowerCase()) ||
            entry.notes.toLowerCase().includes(query.toLowerCase())
        );
        this.renderEntries(filtered);
    }

    renderEntries(entries = this.entries) {
        const container = document.getElementById('entries-list');
        container.innerHTML = '';

        if (entries.length === 0) {
            container.innerHTML = '<div class="no-entries">没有保存的记录</div>';
            return;
        }
        
        // 对条目按创建时间倒序排序（最新的条目显示在最前面）
        const sortedEntries = [...entries].sort((a, b) => {
            const dateA = new Date(a.createdAt || 0);
            const dateB = new Date(b.createdAt || 0);
            return dateB - dateA; // 降序排列
        });
        
        sortedEntries.forEach(entry => {
            const div = document.createElement('div');
            div.className = 'entry-item';
            div.innerHTML = `
                <div class="entry-header">
                    <div><strong>${entry.url || ''}</strong></div>
                </div>
                <div>用户名: ${entry.username || ''}</div>
                <div>备注: ${entry.notes || '无'}</div>
                <div class="entry-footer">
                    <div class="entry-date">添加时间: ${this.formatDate(entry.createdAt)}</div>
                    <div class="entry-actions">
                        <button class="edit-btn" data-id="${String(entry.id)}">编辑</button>
                        <button class="delete-btn" data-id="${String(entry.id)}">删除</button>
                    </div>
                </div>
            `;
            
            // 添加点击事件复制密码
            div.addEventListener('click', (e) => {
                if (!e.target.classList.contains('edit-btn') && !e.target.classList.contains('delete-btn')) {
                    // 使用定时器区分单击和双击
                    if (this.clickTimer) {
                        clearTimeout(this.clickTimer);
                        this.clickTimer = null;
                        // 双击的处理已经在dblclick事件中
                    } else {
                        this.clickTimer = setTimeout(() => {
                            this.clickTimer = null;
                            this.copyPassword(entry);
                        }, this.clickDelay);
                    }
                }
            });

            // 添加编辑按钮事件
            div.querySelector('.edit-btn').addEventListener('click', (e) => {
                e.stopPropagation();
                this.editEntry(entry);
            });

            // 添加删除按钮事件
            div.querySelector('.delete-btn').addEventListener('click', (e) => {
                e.stopPropagation();
                this.deleteEntry(entry);
            });

            // 添加双击事件 - 打开网站并自动填充凭据
            div.addEventListener('dblclick', (e) => {
                e.stopPropagation();
                e.preventDefault();
                this.openAndFill(entry);
            });

            container.appendChild(div);
        });
    }

    copyPassword(entry) {
        navigator.clipboard.writeText(entry.password).then(() => {
            alert('密码已复制到剪贴板');
        }).catch(err => {
            console.error('Failed to copy password:', err);
            alert('复制密码失败');
        });
    }

    clearForm() {
        const addForm = document.getElementById('add-form');
        if (addForm) {
            addForm.reset();
            
            // 确保删除编辑ID
            if (addForm.dataset.editId) {
                console.log('清除编辑标记:', addForm.dataset.editId);
                delete addForm.dataset.editId;
            }
        }
        
        // 重置表单标题为添加模式
        const titleElement = document.querySelector('#add-tab h2');
        if (titleElement) {
            titleElement.textContent = '添加新记录';
        }
    }

    switchTab(tabName) {
        // 更新标签按钮状态
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.tab === tabName);
        });

        // 显示对应的内容
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.toggle('hidden', content.id !== `${tabName}-tab`);
        });
    }

    async editEntry(entry) {
        try {
            if (!entry || entry.id === undefined) {
                showMessage('无效的记录', 'error');
                return;
            }
            
            // 确保ID是数字类型
            const numericId = Number(entry.id);
            if (isNaN(numericId)) {
                console.error('无效的记录ID:', entry.id);
                showMessage('编辑失败：记录ID无效', 'error');
                return;
            }
            
            console.log('准备编辑记录，ID:', numericId, '原始ID类型:', typeof entry.id);
            
            // 检查记录是否存在
            const recordIndex = this.entries.findIndex(e => Number(e.id) === numericId);
            if (recordIndex === -1) {
                console.error('未找到要编辑的记录:', numericId);
                showMessage('要编辑的记录不存在', 'error');
                return;
            }
            
            const record = this.entries[recordIndex];
            console.log('找到要编辑的记录:', record);

            // 填充表单
            document.getElementById('url').value = record.url || '';
            document.getElementById('username').value = record.username || '';
            document.getElementById('password').value = record.password || '';
            document.getElementById('notes').value = record.notes || '';
            
            // 添加编辑标记 - 确保保存为字符串
            const addForm = document.getElementById('add-form');
            if (addForm) {
                addForm.dataset.editId = String(numericId);
                console.log('设置编辑标记:', addForm.dataset.editId);
            }
            
            // 切换到添加/编辑标签页
            this.switchTab('add');
            
            // 更新表单标题
            const titleElement = document.querySelector('#add-tab h2');
            if (titleElement) {
                titleElement.textContent = '编辑记录';
            }
        } catch (error) {
            console.error('编辑记录失败:', error);
            showMessage('编辑记录失败: ' + error.message, 'error');
        }
    }

    async deleteEntry(entry) {
        try {
            if (confirm('确定要删除这条记录吗？')) {
                console.log('Deleting entry:', entry.id);
                // 从数组中移除
                this.entries = this.entries.filter(e => e.id !== entry.id);
                
                console.log('Saving after deletion...');
                const saveResult = await this.saveEntries();
                
                if (saveResult) {
                    // 显示成功消息
                    showMessage('记录已删除', 'success');
                    
                    // 自动同步到服务器
                    try {
                        await this.uploadToServer('update');
                        showMessage('数据已同步到服务器', 'success');
                    } catch (error) {
                        console.error('Sync after delete failed:', error);
                        showMessage('同步到服务器失败: ' + error.message, 'error');
                    }
                }
            }
        } catch (error) {
            console.error('Delete entry failed:', error);
            showMessage('删除失败: ' + error.message, 'error');
        }
    }

    async uploadToServer(operationType = 'update') {
        const settings = await chrome.storage.local.get(['masterKey', 'syncUrl', 'deviceId']);
        if (!settings.masterKey || !settings.syncUrl || !settings.deviceId) {
            throw new Error('请先设置主密钥、同步URL和设备ID');
        }

        const localCrypto = new CryptoUtil(settings.masterKey);
        const encryptedData = await localCrypto.encrypt(this.entries);
        
        const response = await fetch(settings.syncUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 
                data: encryptedData,
                device_id: settings.deviceId,
                operation: operationType
            })
        });

        if (!response.ok) {
            throw new Error(`服务器响应错误: ${response.status}`);
        }

        const result = await response.json();
        if (!result.success) {
            throw new Error(result.error || '服务器处理失败');
        }
    }

    // 新增：打开网站并自动填充功能
    async openAndFill(entry) {
        // 准备URL - 如果没有http前缀，添加https://
        let url = entry.url;
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            url = 'https://' + url;
        }
        
        // 发送消息到后台脚本，请求自动填充
        chrome.runtime.sendMessage({
            type: 'REQUEST_AUTO_FILL',
            data: {
                url: url,
                username: entry.username,
                password: entry.password
            }
        }, response => {
            if (chrome.runtime.lastError) {
                console.error('请求自动填充时出错:', chrome.runtime.lastError);
                showMessage('打开网站时出错', 'error');
            } else if (response && response.success) {
                console.log('已请求自动填充，标签页ID:', response.tabId);
                // 关闭弹窗
                window.close();
            } else {
                showMessage('请求自动填充失败', 'error');
            }
        });
    }

    formatDate(dateString) {
        if (!dateString) return '未知';
        try {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        } catch (e) {
            return '日期格式错误';
        }
    }
}

// 初始化密码管理器
new PasswordManager();

function showMessage(message, type = 'info') {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;
    messageDiv.textContent = message;
    
    // 添加到页面
    document.body.appendChild(messageDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        messageDiv.remove();
    }, 3000);
}

// 添加样式
const style = document.createElement('style');
style.textContent = `
    .message {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 10px 20px;
        border-radius: 4px;
        color: white;
        z-index: 1000;
        animation: slideIn 0.3s ease-out;
    }
    
    .message.success {
        background-color: #4CAF50;
    }
    
    .message.error {
        background-color: #f44336;
    }
    
    .message.info {
        background-color: #2196F3;
    }
    
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    .entry-item {
        border: 1px solid #ddd;
        padding: 10px;
        margin-bottom: 10px;
        border-radius: 4px;
        cursor: pointer;
    }
    
    .entry-item:hover {
        background-color: #f5f5f5;
    }
    
    .entry-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 5px;
    }
    
    .entry-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 5px;
    }
    
    .entry-actions {
        display: flex;
        gap: 5px;
    }
    
    .entry-date {
        font-size: 12px;
        color: #666;
    }
    
    .edit-btn, .delete-btn {
        padding: 2px 8px;
        border: none;
        border-radius: 3px;
        cursor: pointer;
        font-size: 12px;
    }
    
    .edit-btn {
        background-color: #4CAF50;
        color: white;
    }
    
    .delete-btn {
        background-color: #f44336;
        color: white;
    }
    
    .edit-btn:hover {
        background-color: #45a049;
    }
    
    .delete-btn:hover {
        background-color: #da190b;
    }
`;
document.head.appendChild(style);

document.addEventListener('DOMContentLoaded', () => {
    new PasswordManager().renderEntries();
}); 